package com.deyuanyun.pic.pbf.service.impl;


import com.deyuanyun.pic.common.dto.PageJsonBean;
import com.deyuanyun.pic.common.tool.JXL;
import com.deyuanyun.pic.common.util.DateUtil;
import com.deyuanyun.pic.common.util.ObjectUtil;
import com.deyuanyun.pic.common.util.StringUtils;
import com.deyuanyun.pic.pbf.domain.ExternalInspectionVo;
import com.deyuanyun.pic.pbf.domain.PipeBodyDefect;
import com.deyuanyun.pic.pbf.domain.PipeBodyDefectExample;
import com.deyuanyun.pic.pbf.enumeration.DefectStateEnum;
import com.deyuanyun.pic.pbf.enumeration.RepairStateEnum;
import com.deyuanyun.pic.pbf.mapper.ExternalInspectionMapper;
import com.deyuanyun.pic.pbf.mapper.PipeBodyDefectMapper;
import com.deyuanyun.pic.pbf.service.PipeBodyDefectService;

import java.math.BigDecimal;
import java.util.*;

import com.deyuanyun.pic.pipe.domain.Gww;
import com.deyuanyun.pic.pipe.domain.Identification;
import com.deyuanyun.pic.pipe.domain.PipeSegmentInfo;
import com.deyuanyun.pic.pipe.domain.PipeSegmentInfoExample;
import com.deyuanyun.pic.pipe.mapper.ComputeRefUgwMapper;
import com.deyuanyun.pic.pipe.mapper.PipeSegmentInfoMapper;
import com.deyuanyun.pic.settings.controller.dto.MyFileVO;
import com.deyuanyun.pic.settings.domain.base.Attachment;
import com.deyuanyun.pic.settings.domain.pipe.PipeLine;
import com.deyuanyun.pic.settings.domain.pipe.PipeSegment;
import com.deyuanyun.pic.settings.domain.util.DomainInitUtil;
import com.deyuanyun.pic.settings.mapper.base.AttachmentMapper;
import com.deyuanyun.pic.settings.mapper.pipe.PipeLineMapper;
import com.deyuanyun.pic.settings.mapper.pipe.PipeSegmentMapper;
import com.deyuanyun.pic.settings.service.pipe.PipeLineService;
import com.deyuanyun.pic.settings.support.biz.CodeUtil;
import com.deyuanyun.pic.settings.support.cache.SessionCacheSupport;
import org.apache.taglibs.standard.tag.common.xml.ForEachTag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;


@Service
public class PipeBodyDefectServiceImpl implements PipeBodyDefectService {


    //金属损失
    private static final String ML = "1E3290704BF1749EE0530E0AA8C09710";
    //凹陷
    private static final String DENT = "1E3290704BF1749EE0530E0AA8C09720";
    //焊缝异常
    private static final String WAN = "1E3290704BF1749EE0530E0AA8C09730";
    //椭圆变形
    private static final String OVAL = "1E3290704BF1749EE0530E0AA8C09740";
    //类裂纹
    private static final String CRAC = "1E3290704BF1749EE0530E0AA8C09750";
    //损伤缺陷
    private static final String OTHE = "1E3290704BF1749EE0530E0AA8C09760";

    @Resource
    private PipeBodyDefectMapper pipeBodyDefectMapper;
    @Resource
    private ExternalInspectionMapper externalInspectionMapper;
    @Resource
    private PipeSegmentMapper pipeSegmentMapper;
    @Resource
    private PipeSegmentInfoMapper pipeSegmentInfoMapper;
    @Resource
    private AttachmentMapper attachmentMapper;
    @Resource
    private PipeLineService pipeLineService;
    @Resource
    private ComputeRefUgwMapper computeRefUgwMapper;

    private static final Logger logger = LoggerFactory.getLogger(PipeBodyDefectServiceImpl.class);

    public PipeBodyDefect selectByPrimaryKey(String id) {
        return this.pipeBodyDefectMapper.selectByPrimaryKey(id);
    }


    public int updateByPrimaryKeySelective(PipeBodyDefect record) {
        return this.pipeBodyDefectMapper.updateByPrimaryKeySelective(record);
    }

    public int updateByPrimaryKey(PipeBodyDefect record) {
        return this.pipeBodyDefectMapper.updateByPrimaryKey(record);
    }

    @Override
    public int createPipeBodyDefect(PipeBodyDefect record,String att[]) throws Exception {
        //创建id、时间、用户
        DomainInitUtil.initCreateDomain(record);
        //缺陷状态(默认为01）
         record.setDataStated(DefectStateEnum.state01.getCode());
        //维修状态
        record.setRepairState(RepairStateEnum.WAIT_FOR_REPAIR.toString());
        //提交类型--PC端
        record.setApparatusType((short)0);
        //删除标记
        record.setDeleted((short)0);
          //添加非内检缺陷的相对参考点信息
        if(record.getMileage() != null){
            Identification  reference=computeRefUgwMapper.queryReferenceByMile(record.getPipeLineId(),record.getMileage());
            if(reference != null){
                record.setReferenceId(reference.getId());
                record.setReference(reference.getSignNumber());
                BigDecimal distance = record.getMileage().subtract(reference.getMileage());
                record.setReferenceDistance(distance);
            }
            //添加非内检测缺陷的上游环焊缝信息
            Gww ugwNumber = computeRefUgwMapper.queryUgwNumberByMile(record.getPipeLineId(),record.getMileage());
            if(ugwNumber != null){
                record.setUgwNumberId(ugwNumber.getId());
                record.setUgwNumber(ugwNumber.getGwwNumber());
                BigDecimal ugwDistance = (record.getMileage().subtract(ugwNumber.getMileage())).abs();
                record.setDistancetougwNumber(ugwDistance);
            }
        }
        //验证自定义编号是否重复
        if(StringUtils.isNotNullEmpty(record.getCustomNumber())){
            PipeBodyDefectExample example = new PipeBodyDefectExample();
            example.createCriteria().andCustomNumberEqualTo(record.getCustomNumber()).andDeletedEqualTo((short)0);
            List<PipeBodyDefect> pipeDefect = pipeBodyDefectMapper.selectByExample(example);
            if(ObjectUtil.isNotNullEmpty(pipeDefect)){
                Random ne = new Random();//实例化一个random的对象ne
                int randowNum = ne.nextInt(9999 - 1000 + 1) + 1000;//为变量赋随机值1000-9999
                record.setCustomNumber(record.getCustomNumber()+randowNum);
            }
        }else{
            record.setCustomNumber(addRuleIfCustomIsNull(record));
        }

        //计算非内检峰值深度
        BigDecimal maxDepth = null;
        if(record.getPipeLineId() != null){
            PipeSegment segment = pipeSegmentMapper.queryPipeSegmentByMileage(record.getPipeLineId(),record.getMileage());
            PipeSegmentInfoExample segmExample = new PipeSegmentInfoExample();
            if(null != segment){
                segmExample.createCriteria().andPipeSegmentIdEqualTo(segment.getId());
                List<PipeSegmentInfo> infoList = pipeSegmentInfoMapper.selectByExample(segmExample);
                if(infoList != null && infoList.size()!= 0){
                    //得到壁厚
                    BigDecimal wallThicknes = infoList.get(0).getWallthickness();

                    if(wallThicknes != null && record.getDepth() != null){

                        //得到缺陷峰值深度
                        maxDepth = new BigDecimal(record.getDepth().doubleValue()/wallThicknes.doubleValue());
                        maxDepth = maxDepth.multiply(new BigDecimal(100));
                    }
                }
                //写入峰值深度
                record.setMaxDepth(maxDepth != null?maxDepth.setScale(1,BigDecimal.ROUND_DOWN).stripTrailingZeros():null);

            }
        }

        //新增非内检缺陷信息
        int num=this.pipeBodyDefectMapper.insertSelective(record);
        if (num > 0 && att != null && att.length > 0) {

            //增加图片附件
            for (int i = 0; i < att.length; i++) {
                attachmentMapper.updateBusinessIdById(record.getId(), att[i]);
            }
        }

        return num;
    }
    /**
     * pc端不输入缺陷点编号时后台生成编号规则
     * @param defect
     * @return
     * @throws Exception
     */
    private String addRuleIfCustomIsNull(PipeBodyDefect defect) throws Exception {

        PipeLine line = pipeLineService.selectByPrimaryKey( defect.getPipeLineId());
        StringBuffer sb = new StringBuffer();
        sb.append(line.getAbridge());
        String defectType = defect.getDefectType();
        if (ML.equals(defectType)){
            sb.append("ML");
        } else if (DENT.equals(defectType)){
            sb.append("DENT");
        } else if (WAN.equals(defectType)){
            sb.append("WAN");
        } else if (OVAL.equals(defectType)){
            sb.append("OVAL");
        } else if (CRAC.equals(defectType)){
            sb.append("CRAC");
        } else if (OTHE.equals(defectType)){
            sb.append("OTHE");
        }
        sb.append(DateUtil.DateToStringYMd(new Date()));
        Random ne = new Random();//实例化一个random的对象ne
        int x = ne.nextInt(9999 - 1000 + 1) + 1000;//为变量赋随机值1000-9999
        sb.append(x);
        return sb.toString();
    }

    @Override
    public List<ExternalInspectionVo> queryData(Map param) {
        List<ExternalInspectionVo> list=this.externalInspectionMapper.queryData(param);
        return   list;
    }

    @Override
    public ExternalInspectionVo queryDefectById(String id) {
        Map param = new HashMap();
        param.put("id",id);
        List<ExternalInspectionVo> defectList =this.externalInspectionMapper.queryData(param);
        ExternalInspectionVo defect = null;
        if(defectList != null && defectList.size() != 0){
             defect = defectList.get(0);
        }

        return defect;
    }

    @Override
    public int updateToDeleteById(PipeBodyDefect defect) {
        int i = this.externalInspectionMapper.updateToDeleteById(defect);
        if( i > 0)
        {
            //修改时间，用户，备注
            DomainInitUtil.initUpdateDomain(defect,"删除非内检测缺陷");
            //删除对应附件
            this.attachmentMapper.updateByBusinessId(defect.getId());
        }
        return i;
    }


    @Override
    public List<String[]> queryDataExport(Map param) {

        List  defect= this.externalInspectionMapper.queryData(param);

        List<String[]> lsr = JXL.toListFormVO(defect, "yyyy-MM-dd HH:mm:ss");

        return lsr;
    }
    @Override
    public int queryCountByState(Map param) {
        int i=this.externalInspectionMapper.queryCountByState(param);
        return  i;
    }

    @Override
    public String queryRepiarTabById(String repiarId ) {

        String repiarTab =this.externalInspectionMapper.queryRepiarTabById(repiarId);
        return repiarTab;
    }

    @Override
    public PipeBodyDefect queryReferenceByMile(PipeBodyDefect record) {
        if(record.getMileage() != null){
            Identification  reference=computeRefUgwMapper.queryReferenceByMile(record.getPipeLineId(),record.getMileage());
            record.setReferenceId(reference.getId());
            record.setReference(reference.getSignNumber());
            BigDecimal distance = (reference.getMileage().subtract(record.getMileage())).abs();
            record.setReferenceDistance(distance);
        }
        return record;
    }

    @Override
    public PipeBodyDefect queryUgwNumberByMile(PipeBodyDefect record) {
        if(record.getMileage() != null) {
            Gww ugwNumber = computeRefUgwMapper.queryUgwNumberByMile(record.getPipeLineId(),record.getMileage());
            record.setUgwNumberId(ugwNumber.getId());
            record.setUgwNumber(ugwNumber.getGwwNumber());
            BigDecimal distance = (record.getMileage().subtract(ugwNumber.getMileage())).abs();
            record.setDistancetougwNumber(distance);
        }
        return record;
    }

    @Override
    public  List<Map<String, Object>> queryOtherInspection(Map<String, Object> param) {
        List<Map<String, Object>> list=externalInspectionMapper.queryOtherInspection(param);
        for(Map<String, Object> m:list)
        {
            m.put("TYPE", CodeUtil.getName((String)m.get("TYPE")));
            if(m.get("TYPE") == null)
            {
                m.put("TYPE","未知");
            }
        }
        return list;
    }

}